package com.dss.auto_deploy.rabbitmq.config;

import com.alibaba.fastjson.JSON;
import com.dss.auto_deploy.vo.MqMsgVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Description:
 * @ClassName: RabbitSender
 * @author: dongshoushan
 * @date: 2020年05月26日 16:14
 */
@Component
@Slf4j
public class RabbitSender {
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private ConfirmCallBackHandler confirmCallBackHandler;
    @Resource
    private ReturnCallBackHandler returnCallBackHandler;
    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 每次获取新的RabbitTemplate
     *
     * @return
     */
    private RabbitTemplate getScopeRabbitTemplate() {
        RabbitTemplate scopeRabbitTemplate = (RabbitTemplate) applicationContext.getBean("scopeRabbitTemplate");
        log.info("获取新的RabbitTemplate:{}", scopeRabbitTemplate);
        return scopeRabbitTemplate;
    }


    /**
     * 发送主题模式消息
     *
     * @param mqMsgVo
     */
    public void sendRabbitMQ(MqMsgVo mqMsgVo) {
        RabbitTemplate rabbitTemplate = getScopeRabbitTemplate();
        rabbitTemplate.setConfirmCallback(confirmCallBackHandler);
        rabbitTemplate.setReturnCallback(returnCallBackHandler);
        String string = JSON.toJSONString(mqMsgVo);
        //log.info("rabbitMQ发送信息：{}", string);
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString().replace("-", ""));
        rabbitTemplate.convertAndSend(mqMsgVo.getExchangeName(), mqMsgVo.getRoutingKey(), string, correlationData);
    }

}
